package conn

import (
	"flag"
	"fmt"
	"github.com/go-ini/ini"
	"github.com/shenshouer/ftp4go"
	"os"
	"strings"
)

type Config struct {
	DictRule []string
	FileRule []string
	Dir string
	Concurrency int
	FtpUrl string
	FtpPort int
	FtpRoot string
}

var (
	fileConf string
	Conf Config
)

func init(){
	flag.StringVar(&fileConf,"c","ftp.conf","配置文件的路径")
	flag.Parse()
	cfg, err := ini.Load(fileConf)
	if err != nil {
		fmt.Printf("加载配置文件失败: %v", err)
		os.Exit(1)
	}
	Conf.Dir  = cfg.Section("ftp").Key("downDir").String()
	Conf.Concurrency,_  = cfg.Section("ftp").Key("concurrency").Int()
	Conf.FtpUrl = cfg.Section("ftp").Key("ftpUrl").String()
	Conf.FtpPort,_ = cfg.Section("ftp").Key("ftpPort").Int()
	Conf.FtpRoot = cfg.Section("ftp").Key("ftpRoot").String()
	Conf.DictRule = strings.Split(cfg.Section("ftp").Key("dictionRule").String(),",")
	Conf.FileRule = strings.Split(cfg.Section("ftp").Key("fileRule").String(),",")
}


func Connection() *ftp4go.FTP{
	ftpClient := ftp4go.NewFTP(0) // 1 for debugging
	_, err := ftpClient.Connect(Conf.FtpUrl, Conf.FtpPort, "")
	if err != nil {
		fmt.Println("连接失败", err.Error())
		return nil
	}
	_, err = ftpClient.Login("", "", "")
	if err != nil {
		fmt.Println("登录失败")
		return nil
	}
	_,_ = ftpClient.Cwd(Conf.FtpRoot)
	return ftpClient
}





